<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :model-value="visible"
      :title="title"
      width="1100px"
      draggable
      align-center
      destroy-on-close
      @close="closeDialog"
      class="maxhDialog"
    >
      <el-row>
        <!-- 用户列表 -->
        <el-col>
          <div class="search-container" style="padding: 18px 15px 0">
            <el-form
              :model="searchParam"
              :inline="true"
              class="demo-form-inline"
            >
              <el-form-item label="物料编号">
                <el-input
                  v-model="searchParam.materialCode"
                  placeholder="请输入物料编号"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item label="物料名称">
                <el-input
                  v-model="searchParam.materialName"
                  placeholder="请输入物料名称"
                  clearable
                  @keyup.enter="search"
                />
              </el-form-item>
              <el-form-item label="物料类型">
                <el-select
                  v-model="searchParam.materialType"
                  clearable
                  :disabled="sureMaterialType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'MaterialType'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="Number(item.value)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="reset"><i-ep-refresh />重置</el-button>
                <!-- <el-button type="primary" @click="toggleSearchArea" link>
                  {{ isExpanded ? "收起" : "展开" }}
                  <el-icon v-if="isExpanded" class="el-icon--right">
                    <i-ep-arrowUp color="#409EFC" />
                  </el-icon>
                  <el-icon v-else class="el-icon--right">
                    <i-ep-arrowDown color="#409EFC" />
                  </el-icon>
                </el-button> -->
              </el-form-item>
            </el-form>
          </div>

          <el-card shadow="never" class="table-container">
            <el-table
              ref="materialTable"
              v-loading="loading"
              :data="tableData"
              :key="Math.random"
              @select="handleSelectionChange"
              @select-all="handleSelectAll"
              height="444px"
              row-key="materialCode"
              border
              :cell-style="{ 'text-align': 'center' }"
            >
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column
                label="物料编号"
                prop="materialCode"
                min-width="120"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="物料名称"
                prop="materialName"
                min-width="150"
                show-overflow-tooltip
                align="left"
              >
                <template #default="scope">
                  <span style="text-align: left">
                    {{ scope.row.materialName }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                label="物料类型"
                prop="materialType"
                min-width="120"
                show-overflow-tooltip
                align="left"
                v-show="!sureMaterialType"
              >
                <template #default="scope">
                  {{ useDictionary("MaterialType", scope.row.materialType) }}
                </template>
              </el-table-column>
              <el-table-column
                label="物料组"
                prop="materialGroupName"
                min-width="150"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="短号"
                prop="shortCode"
                min-width="100"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="外来编号"
                prop="srcCode"
                min-width="100"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="图号"
                prop="figureNumber"
                min-width="100"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="国产件标识"
                prop="lcCkd"
                min-width="100"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  <el-tag type="success" v-if="scope.row.lcCkd === 1"
                    >是</el-tag
                  >
                  <el-tag type="info" v-else>否</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="物料状态"
                prop="materialState"
                min-width="90"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ useDictionary("MaterialState", scope.row.materialState) }}
                </template>
              </el-table-column>
              <el-table-column
                label="包装物料类别"
                prop="packageType"
                min-width="110"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ useDictionary("MaterialState", scope.row.materialState) }}
                </template>
              </el-table-column>
              <el-table-column
                label="包装单位类别"
                prop="handlingUnitType"
                min-width="110"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ useDictionary("MaterialState", scope.row.materialState) }}
                </template>
              </el-table-column>
              <el-table-column
                label="物料规格"
                prop="materialSpecification"
                min-width="100"
                show-overflow-tooltip
                align="left"
              />
              <el-table-column
                label="计量单位"
                prop="unit"
                min-width="90"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ useDictionary("MeasurementUnit", scope.row.unit) }}
                </template>
              </el-table-column>
              <el-table-column
                label="是否自有资产"
                prop="ownAssets"
                min-width="110"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  {{ useDictionary("MeasurementUnit", scope.row.unit) }}
                </template>
              </el-table-column>
              <el-table-column
                label="启用状态"
                prop="enabled"
                min-width="100"
                show-overflow-tooltip
                align="center"
              >
                <template #default="scope">
                  <el-tag type="success" v-if="scope.row.enabled === 1"
                    >启用</el-tag
                  >
                  <el-tag type="info" v-else>停用</el-tag>
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              small
              background
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[20px]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable } from "@/utils/useTable";
import { ElTable, ElMessage } from "element-plus";
import { useDictionary } from "@/utils/useTable";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook(); // 定义

defineOptions({
  name: "SELECTMATERIALDIALOG",
  inheritAttrs: false,
});

interface SelectOption {
  id?: string;
  materialCode?: string;
}
const emit = defineEmits(["update:visible", "echo-info"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "物料选择";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Array,
    default: () => {
      return [];
    },
  },
  isMultiple: {
    type: Boolean,
    default: false,
  },
  materialType: {
    type: Number,
    default: null,
  },
});

const { visible, isMultiple } = toRefs(props);
const isExpanded = ref(false);
// 右侧人员选择操作
const materialTable = ref(ElTable);
// 表格选择
const totalMultipleSelection: any = ref([]);
/** 弹窗展开 初始化数据 */
const totalMultipleIds: any = ref([]);
/** 弹窗展开 初始化数据 */
const oldTotalSelection: any = ref([]);

// 请求参数
const requestApi = "/mdm/mdmmaterial/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {
  // sort: {
  //   column: "last_update_time",
  //   orderBy: "desc",
  // },
};

// 初始化搜索参数数据
const searchParamInit = {
  materialCode: "",
  materialName: "",
  materialType: props.materialType || "",
  plantId: "",
};

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  loading,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError
);

onMounted(() => {
  getTableList();
});

function toggleSearchArea() {
  isExpanded.value = !isExpanded.value;
  if (!isExpanded.value) {
    searchParam.value.materialType = "";
  }
}

// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}

// 表格触发全选
function handleSelectAll(selecteds: any) {
  if (isMultiple.value) {
    const currentSelection = deepCopy(totalMultipleSelection.value);
    const ids = deepCopy(totalMultipleIds.value);
    if (selecteds.length) {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.materialCode);
        if (indexId < 0) {
          totalMultipleSelection.value.push(item);
        }
      });
    } else {
      tableData.value.map((item: SelectOption) => {
        const indexId = ids.indexOf(item.materialCode);
        if (indexId > -1) {
          currentSelection.splice(indexId, 1);
          ids.splice(indexId, 1);
        }
      });
      totalMultipleSelection.value = currentSelection;
    }
  } else {
    delAll();
    ElMessage.warning("单选模式不允许全选");
  }
}
// 表格触发单个选择
function handleSelectionChange(val: any, row: SelectOption) {
  let addOptions = false;
  val?.map((item: SelectOption) => {
    if (item.materialCode === row.materialCode) {
      addOptions = true;
    }
  });
  if (!addOptions) {
    const index = totalMultipleIds.value.indexOf(row.materialCode);
    totalMultipleSelection.value.splice(index, 1);
  } else {
    if (isMultiple.value) {
      totalMultipleSelection.value.push(row);
    } else {
      delAll();
      materialTable.value.toggleRowSelection(row, true);
      totalMultipleSelection.value = [row];
    }
  }
  console.log(totalMultipleSelection.value);
}

// 全部清除
function delAll() {
  totalMultipleSelection.value = [];
  materialTable.value.clearSelection();
}

watch(
  () => totalMultipleSelection,
  async (newVal: any) => {
    const ids: any = [];
    newVal.value?.map((item: SelectOption) => ids.push(item.materialCode));
    totalMultipleIds.value = ids;
  },
  { deep: true }
);

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
function dataCallBack(data: any) {
  setTimeout(() => {
    data.map((item: SelectOption) => {
      if (totalMultipleIds.value.includes(item.materialCode)) {
        materialTable.value?.toggleRowSelection(item, true);
      }
    });
  }, 0);
  return data;
}

watch(
  () => props.visible,
  async (newVal: boolean) => {
    if (newVal) {
      totalMultipleSelection.value = deepCopy(props.data);
      oldTotalSelection.value = deepCopy(props.data);
      dataCallBack(tableData.value);
    }
  }
);

const sureMaterialType = ref(false);
watch(
  () => props.materialType,
  async (newVal) => {
    if (newVal) {
      searchParam.value.materialType = newVal;
      sureMaterialType.value = true;
    } else {
      searchParam.value.materialType = null;
      sureMaterialType.value = false;
    }
  },
  {
    immediate: true,
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  totalMultipleSelection.value = oldTotalSelection.value;
  dataCallBack(tableData.value);
  emit("update:visible", false);
}

/** 确定提交 */
async function handleSubmit() {
  if (!isMultiple.value && totalMultipleSelection.value.length > 1) {
    ElMessage.error("请选择单个物料");
  } else {
    emit("update:visible", false);
    emit("echo-info", totalMultipleSelection.value);
  }
}
// 组件销毁时调用
onBeforeUnmount(() => {
  emit("update:visible", false);
  closeDialog();
});
</script>

<style lang="scss" scoped>
:deep(.maxhDialog .el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
  .mini-search {
    padding: 8px 12px;
  }
  .el-card__body {
    padding: 15px;
  }
  .el-form--inline .el-form-item {
    margin-right: 20px;
    margin-bottom: 18px;
  }
}
</style>
